package com.leetcode.algorithm.y22.m07;

import com.leetcode.algorithm.common.TreeNode;

/**
 * 235. 二叉搜索树的最近公共祖先
 * 
 * https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
 * 
 * @author jie.deng
 *
 */
class Question0235Solution01 {

	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		if (root == null || root == p || root == q) {
			return root;
		}
		if (p == q) {
			return p;
		}
		int left = 0;
		int right = 0;
		if (p.val > q.val) {
			left = q.val;
			right = p.val;
		} else {
			left = p.val;
			right = q.val;
		}
		return lowestCommonAncestor(root, left, right);
	}

	private TreeNode lowestCommonAncestor(TreeNode root, int left, int right) {
		if (root.val < left) {
			return lowestCommonAncestor(root.right, left, right);
		} else if (root.val > right) {
			return lowestCommonAncestor(root.left, left, right);
		}
		return root;
	}

}